import Bread from '@/component/bread/bread'
import { Button, Descriptions, Collapse, message, Modal } from 'antd'
import { ExclamationCircleOutlined } from '@ant-design/icons'

import axios from '@/http'
import NavHeader from './navHeader/nabHeader'
import { ForwardedRef, useContext, useEffect, useRef, useState } from 'react'
import NavModal from './navModal/navModal'
import { TNav, TStore } from '@type'
import { AppContext } from '@/App'
const { confirm } = Modal

const { Panel } = Collapse

type TRenderNav<T> = {
  category: string
  categoryDesc: string
  navInfo: T[]
}
type TDescribe = {
  label: string
  labelStyle: any
  render: () => JSX.Element
}
const Nav = () => {
  const {
    store: { status }
  } = useContext<TStore>(AppContext)
  useEffect(() => {
    getNavList()
  }, [])
  const describeConfig = (item: TNav): TDescribe[] => {
    return [
      {
        label: 'logo',
        labelStyle: { fontSize: '13px', width: '105px' },
        render: () =>
          item.otcPath ? (
            <img src={item.otcPath} alt="logo" style={{ backgroundColor: item.bgColor }} width={30} height={30} />
          ) : (
            <span>无图片</span>
          )
      },
      {
        label: '描述',
        labelStyle: { fontSize: '13px' },
        render: () => <span style={{ color: '#333', fontSize: '13px' }}>{item.otcDescribe}</span>
      },
      {
        label: '应用链接',
        labelStyle: { fontSize: '13px' },
        render: () => (
          <a href={item.path} target="_blank" rel="noreferrer">
            {item.path}
          </a>
        )
      },
      {
        label: 'git地址',
        labelStyle: { fontSize: '13px' },
        render: () => (
          <a href={item.name} target="_blank" rel="noreferrer">
            {item.name}
          </a>
        )
      }
    ]
  }

  const [navList, setNavList] = useState<TRenderNav<TNav>[]>([])
  const getNavList = () => {
    axios.get('/navigation/search').then(({ data }) => {
      let res = initResData(data.data)
      data.error === -1 && setNavList(res)
    })
  }
  const initResData = (data: TNav[]) => {
    const NavInfo: TRenderNav<TNav>[] = []
    const temArr: Array<string> = []
    data.forEach(item => {
      temArr.includes(item.category)
        ? NavInfo.find(navitem => navitem.category === item.category)!.navInfo.push(item)
        : NavInfo.push({
            category: item.category,
            categoryDesc: item.categoryDesc,
            navInfo: [item]
          }) && temArr.push(item.category)
    })
    return NavInfo
  }
  const delNav = (id: number) => {
    confirm({
      title: '删除导航?',
      icon: <ExclamationCircleOutlined />,
      content: '你确定要删除该导航？',
      okText: '确定',
      okType: 'danger',
      cancelText: '取消',
      onOk() {
        startDel(id)
      }
    })
  }
  const startDel = (id: number) => {
    axios
      .post('/navigation/del', {
        id,
        status
      })
      .then(res => {
        if (res.data.error === -1) {
          message.success('删除成功')
          getNavList()
        }
      })
  }
  const [editNavData, setEditNavData] = useState<TNav | undefined>()
  const editNav = (item?: TNav) => {
    item ? setEditNavData(item) : setEditNavData(undefined)
    NavDom.current?.showModal()
  }
  const NavDom = useRef<{ showModal: Function }>(null)
  const addCate = (navitem: TRenderNav<TNav>) => {
    const addCateInfo = (e: React.MouseEvent<HTMLElement, MouseEvent>, navitem: TRenderNav<TNav>) => {
      const { category, categoryDesc } = navitem
      e.stopPropagation()
      const nav: TNav = {
        bgColor: '',
        category: '',
        categoryDesc: '',
        id: 0,
        name: '',
        otcDescribe: '',
        otcName: '',
        otcPath: '',
        path: ''
      }
      editNav({ ...nav, category, categoryDesc })
    }
    return (
      <Button type="link" onClick={event => addCateInfo(event, navitem)}>
        新增
      </Button>
    )
  }
  return (
    <>
      <Bread bread={['导航', '导航管理']}></Bread>
      <NavHeader openModal={editNav} navItem={navList}></NavHeader>
      <NavModal ref={NavDom} editData={editNavData} search={getNavList}></NavModal>
      <div style={{ marginTop: '80px' }}>
        <Collapse defaultActiveKey={['Vue']}>
          {navList.map(navitem => (
            <Panel
              extra={addCate(navitem)}
              header={
                <>
                  <span>{navitem.category}</span>
                  <span style={{ marginLeft: '24px', color: '#888', fontSize: '13px' }}>{navitem.categoryDesc}</span>
                </>
              }
              key={navitem.category}
            >
              <div style={{ display: 'flex', flexWrap: 'wrap', justifyContent: 'space-between' }}>
                {navitem.navInfo.map((item, index) => (
                  <Descriptions
                    key={index}
                    bordered
                    style={{ width: '45%', margin: '8px 0' }}
                    title={item.otcName}
                    size={'middle'}
                    column={1}
                    extra={
                      <>
                        <Button type="primary" onClick={() => editNav(item)}>
                          编辑
                        </Button>
                        <Button type="primary" danger style={{ marginLeft: '16px' }} onClick={() => delNav(item.id)}>
                          删除
                        </Button>
                      </>
                    }
                  >
                    {describeConfig(item).map(({ label, labelStyle, render }, index) => (
                      <Descriptions.Item key={index} label={label} labelStyle={labelStyle}>
                        {render()}
                      </Descriptions.Item>
                    ))}
                  </Descriptions>
                ))}
              </div>
            </Panel>
          ))}
        </Collapse>
      </div>
    </>
  )
}
export default Nav
